<template>
  <div class="package-container">
    <Breadcrumb :opt-data="breadcrumbOptData"></Breadcrumb>
    <PageLayout>
      <div class="table-container height-100">
        <el-tabs v-model="activeName" @tab-click="getPackageData">
          <el-tab-pane label="分控" name="ezControl"></el-tab-pane>
          <el-tab-pane label="控制屏" name="controlPad"></el-tab-pane>
        </el-tabs>
        <el-table :data="packageData" stripe border height="calc(100% - 90px)" v-loading="tableLoading">
          <el-table-column prop="version" label="版本号">
          </el-table-column>
          <el-table-column prop="type" label="设备类型">
            <template slot-scope="scope">
              <span>{{scope.row.type === 'ezControl' ? '分控' : '平板'}}</span>
            </template>
          </el-table-column>
          <el-table-column label="安装包" width="300">
            <template slot-scope="scope">
              <div v-if="scope.row.files">
                <p  @click="downloadFile(item)" v-for="(item,index) in  scope.row.files"
                   :key="index">
                  <span class="font-weight-bold">{{item.fileDesc}}：</span>
                  <span class="package-tag">{{item.fileName}}</span></p>
              </div>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态">
            <template slot-scope="scope">
              <span>{{packageStatus.find(type => type.value === scope.row.status).label}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="changelog" label="版本描述">
            <template slot-scope="scope">
              <span class="package-tag" @click="showPackageDesc(scope.row.changelog)">查看描述</span>
            </template>
          </el-table-column>
          <el-table-column prop="date" sortable label="更新时间" width="150">
            <template slot-scope="scope">
              {{formatMeta(scope.row).lastUpdatedAtFromNow}}
            </template>

          </el-table-column>
          <el-table-column prop="address" label="操作" width="280" v-if="userInfo.role === 'admin'">
            <template slot-scope="scope">
              <el-button type="default" size="mini" @click="packageManage(scope.row)">安装包管理
              </el-button>
              <el-button type="default" size="mini" @click="packageEdit(scope.row)">编辑
              </el-button>
              <el-button type="default" size="mini" @click="packageDelete(scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes=" [10, 15, 30, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next"
          class="table-pagination width-100 mar-top-5"
          :total="total">
        </el-pagination>
      </div>
      <el-dialog
        :visible.sync="showPackageDialog"
        :close-on-click-modal="false"
        :title="`${!isEditPackage ? '新增' : '编辑'}版本`"
        width="700px"
        center>
        <el-form
          v-loading="packageFormLoading"
          :ref="packageFormRef"
          :model="packageForm"
          :rules="packageFormRules"
          size="small"
          label-width="80px">
          <el-form-item label="版本号" prop="version">
            <el-input v-model="packageForm.version" class="width-100" placeholder="请填写设备版本"
                      :disabled="isEditPackage"></el-input>
          </el-form-item>
          <el-form-item label="设备类型" prop="type">
            <el-select v-model="packageForm.type" filterable clearable class="width-100" placeholder="请选择设备类型"
                       :disabled="isEditPackage">
              <el-option :label="device.label" :value="device.value" :key="idx"
                         v-for="(device, idx) in packageDevice"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="版本状态" prop="status">
            <el-select v-model="packageForm.status" filterable clearable class="width-100" placeholder="请选择版本状态">
              <el-option :label="model.label" :value="model.value" :key="idx"
                         v-for="(model, idx) in packageStatus"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="版本描述" prop="changelog">
            <el-input type="textarea" v-model="packageForm.changelog" placeholder="请填写版本描述" rows="5"></el-input>
          </el-form-item>
        </el-form>
        <div class="text-align-right">
          <el-button size="medium" @click="clickCancelBtn">取消</el-button>
          <el-button size="medium" type="primary" @click="clickSubmitBtn">保存</el-button>
        </div>
      </el-dialog>
      <!--安装包管理-->
      <el-dialog title="安装包管理" :visible.sync="showDocumentDialog" :close-on-click-modal="false" width="680px"
                 center>
        <p class="flex-justify-end">
          <el-button type="primary" size="small" @click="uploadFiles">上传</el-button>
        </p>
        <el-table :data="packageFiles.files" style="width: 100%" border height="400">
          <el-table-column prop="fileName" label="文件名" show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="fileDesc" label="平台">
          </el-table-column>
          <el-table-column prop="address" label="操作">
            <template slot-scope="scope">
              <el-button type="default" size="mini" @click="downloadFile(scope.row)">下载
              </el-button>

              <el-button type="danger" size="mini" @click="deleteFiles(scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <p style="text-align:center" v-if="packageFiles.length > 0">共{{packageFiles.length}}条</p>
      </el-dialog>
      <el-dialog title="上传安装包" :visible.sync="showDocumentUploadDialog" width="680px" center
                 :close-on-click-modal="false"
                 @close="cancelUpload"
                 v-loading="uploadLoading">
        <el-form
          :ref="uploadPackageFormRef"
          :model="uploadPackageForm"
          :rules="uploadPackageFormRules"
          size="small"
          label-width="100px">
          <el-form-item label="平台" prop="platform">
            <el-select v-show="packageFiles.type==='ezControl'" v-model="uploadPackageForm.platform" filterable
                       clearable class="width-100" placeholder="平台">
              <el-option :label="model.label" :value="model.value" :key="idx"
                         v-for="(model, idx) in ezControlPlatform"></el-option>
            </el-select>
            <el-select v-show="packageFiles.type==='controlPad'" v-model="uploadPackageForm.platform" filterable
                       clearable class="width-100" placeholder="平台">
              <el-option :label="model.label" :value="model.value" :key="idx"
                         v-for="(model, idx) in ezPadPlatform"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择文件">
            <el-upload :auto-upload="false" ref="uploadref" action="action" :limit="3" :on-exceed="handleExceed"
                       multiple
                       :file-list="fileList" :on-remove="handleRemove"
                       :on-change="handleChange">
              <i class="el-icon-upload"></i>
              <el-button size="small" type="primary">选择文件</el-button>
            </el-upload>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancelUpload">取 消</el-button>
          <el-button type="primary" @click="closeUpload">确 定</el-button>
        </span>
      </el-dialog>
      <!--查看详情-->
      <el-dialog
        :visible.sync="showPackageDescDialog"
        :close-on-click-modal="false"
        title="查看版本描述详情"
        width="700px"
        center>
        <span v-html="formatChangelog(changelog)"></span>
      </el-dialog>
    </PageLayout>
  </div>
</template>
<script>
  import {packageStatus, packageDevice, ezControlPlatform, ezPadPlatform} from "@/config/common";
  import {msgCode} from "@/config/string";
  import {confirmHandle, messageHandle, getUserInfo,formatMeta} from "@/utils";

  import EZTable from '../../components/table/EZTable';
  import {assetBaseUrl} from "@/config/env";

  export default {
    name: "PackageManagement",
    components: {EZTable},
    data() {
      return {
        userInfo: getUserInfo(),
        tableLoading: true,
        packageData: [],
        showPackageDialog: false,
        packageFormLoading: false,
        packageForm: {},
        packageFormRules: {
          version: [
            {required: true, message: '请填写版本号', trigger: 'blur'}
          ],
          type: [
            {required: true, message: '请选择设备类型', trigger: 'blur'}
          ],
          status: [
            {required: true, message: '请选择版本状态', trigger: 'blur'}
          ],
          changelog: [
            {required: true, message: '请填写版本描述', trigger: 'blur'}
          ],
        },
        packageFormRef: 'packageFormRef',
        isEditPackage: false,
        packageStatus: packageStatus,
        packageDevice: packageDevice,
        ezControlPlatform: ezControlPlatform,
        ezPadPlatform: ezPadPlatform,
        showDocumentDialog: false,
        packageFiles: [],
        //上传安装包
        showDocumentUploadDialog: false,
        action: `${assetBaseUrl}/file/upload`,
        fileList: [],
        uploadLoading: false,
        uploadPackageForm: {
          assetType: 'ezControl',
          platform: '',
        },
        uploadPackageFormRules: {
          platform: [
            {required: true, message: '请选择平台', trigger: 'blur'}
          ],
        },
        uploadPackageFormRef: 'uploadPackageFormRef',
        activeName: 'ezControl',
        currentPage: 1,
        total: 0,
        pageSize: 10,
        showPackageDescDialog: false,
        changelog: '',
        formatMeta,

      }
    },
    computed: {
      breadcrumbOptData() {
        if (this.userInfo.role === 'admin') {
          return [
            {
              type: 'btn',
              label: '新增版本',
              icon: 'icon-tianjia',
              callback: () => {
                this.clickCreateBtn();
              }
            },
          ];
        }
      },
    },
    activated() {

      this.initPackageForm();
      this.getPackageData();

    },
    methods: {

      initPackageForm() {
        this.packageForm = {
          type: '',
          version: '',
          changelog: '',
          status: '',
        }
      },
      resetPackageForm() {
        this.initPackageForm();
        const packageForm = this.$refs[this.packageFormRef];
        packageForm && packageForm.resetFields();
      },
      clickCreateBtn() {
        this.isEditPackage && this.resetPackageForm();
        this.showPackageDialog = true;
        this.isEditPackage = false;
      },
      getPackageDetailData(id) {
        API.packageType.packageDetail({_id: id}).then(result => {
          this.packageFiles = result.data;
        });
      },
      getPackageData() {
        this.tableLoading = true;
        const selector = {type: this.activeName};
        const tableParam = {
          pageNo: this.currentPage,
          pageSize: this.pageSize
        };
        API.packageType.packageList({selector, ...tableParam}).then(result => {
          this.tableLoading = false;
          const {data = [], total = 0} = result;
          this.packageData = data
          this.total = total;
        }).catch(err => {
          console.log('err', err)
          this.tableLoading = false;
        });
      },

      deletePackage(device = {}) {
        confirmHandle({label: `确定要删除版本：${device.version} 吗?`}).then(() => {
          API.packageType.packageDelete({_id: device._id}).then(result => {
            messageHandle({code: msgCode.DELETE_SUCCESS, title: '版本'});
            this.getPackageData();
            this.resetPackageForm();
          });
        }).catch(() => {
        });
      },
      clickCancelBtn() {
        this.showPackageDialog = false
      },
      clickSubmitBtn() {
        this.$refs[this.packageFormRef].validate((valid) => {
          if (!valid) return;
          this.packageFormLoading = true;
          if (!this.isEditPackage) {
            API.packageType.packageAdd(this.packageForm).then(result => {
              messageHandle({code: msgCode.ADD_SUCCESS, title: '版本'});
              this.showPackageDialog = false;
              this.packageFormLoading = false;
              this.getPackageData();
              this.resetPackageForm();
            }).catch(err => {
              console.log('err', err)
              this.packageFormLoading = false;
            });
          } else {
            API.packageType.packageEdit(this.packageForm).then(result => {
              messageHandle({code: msgCode.EDIT_SUCCESS, title: '版本'});
              this.showPackageDialog = false;
              this.packageFormLoading = false;
              this.getPackageData();
              this.resetPackageForm();
            }).catch(err => {
              console.log('err', err)
              this.packageFormLoading = false;
            });
          }
        });
      },
      uploadFiles() {
        this.showDocumentUploadDialog = true
      },
      deleteFiles(row) {
        confirmHandle({label: `是否要删除：${row.fileName} 的安装包吗?`}).then(() => {
          API.packageType.packageFileDelete({versionId: this.packageFiles._id, fileId: row.fileId}).then(result => {
            messageHandle({code: msgCode.DELETE_SUCCESS, title: '安装包'});
            this.getPackageDetailData(this.packageFiles._id)
            this.getPackageData()
          }).catch(err => {
            console.log('err', err)

          });
        }).catch(() => {
        });
      },
      downloadFile(row) {
        let a = document.createElement('a')
        a.target = "_blank";
        a.href = `${assetBaseUrl}/file/download/${row.filePath}`
        a.download = row.fileName
        a.click()
      },
      handleExceed() {
        this.$message.warning(
          `当前限制选择 1 个文件，已选择1个文件`
        );
      },
      handleChange(file, fileList) {
        this.fileList = fileList;
      },
      handleRemove(file, fileList) {// 删除上传文件
        this.fileList = fileList
      },
      httpUpload() {
        this.uploadLoading = true
        const formData = new FormData();
        this.fileList.forEach((file) => {
          formData.append("file", file.raw);
        })
        const params = {
          type: 'installPackage',
          assetType: this.packageFiles.type,
          versionId: this.packageFiles._id,
          platform: this.uploadPackageForm.platform
        };
        API.packageType.packageUpload(formData, params).then(resp => {
          if (resp.data === 1) {
            //正确
            this.showDocumentUploadDialog = false
            this.getPackageDetailData(this.packageFiles._id)
            this.fileList = []
            this.$message.success(`上传成功`);
            this.uploadPackageForm.platform = ''
            this.getPackageData()
          } else {
            this.$message.error(resp.data.errors[0].errMsg);
          }
          this.uploadLoading = false

        }).catch(err => {
          console.log('##### err #####', err);
          this.uploadLoading = false
        });
      },
      closeUpload() {
        this.$refs[this.uploadPackageFormRef].validate((valid) => {
          if (!valid) return;
          if (this.fileList.length > 0) {
            this.httpUpload()
          } else {
            this.$message.warning('请选择上传文件');
            this.uploadLoading = false
          }
        })
      },
      cancelUpload() {
        this.fileList = []
        this.showDocumentUploadDialog = false
        this.uploadPackageForm.platform = ''
      },
      packageManage(row) {
        this.showDocumentDialog = true;
        this.getPackageDetailData(row._id);
      },
      packageEdit(row) {
        this.showPackageDialog = true;
        this.isEditPackage = true;
        this.packageForm = row;
      },
      packageDelete(row) {
        this.deletePackage(row);
      },
      handleSizeChange(val) {
        this.pageSize = val;
        this.getPackageData();
      },
      handleCurrentChange(val) {
        this.currentPage = val;
        this.getPackageData();
      },
      formatChangelog(changelog) {
        // 将换行符替换为 <br> 标签，以便在 HTML 中正确显示

        return changelog.split("\n").join("<br>");
      },
      //查看版本详情
      showPackageDesc(changelog) {
        this.showPackageDescDialog = true;
        this.changelog= changelog;
      }
    },

  }
</script>

<style scoped lang="less">
  .package-tag {
    cursor: pointer;
    color: #2D69E0;
  }
  .package-tag:hover {
    text-decoration: underline;
  }
</style>
